#第一题
import tushare as ts
# 初始化pro接口
pro = ts.pro_api('3171f5df9baa3e897b247de0a2c27026b858e49ba2a53d3280b44010')
# 拉取数据
df = pro.daily(**{
    "ts_code": "",
    "trade_date": "",
    "start_date": 20250331,
    "end_date": 20250331,
    "offset": "",
    "limit": ""
}, fields=[
    "ts_code",
    "trade_date",
    "open",
    "high",
    "low",
    "close",
    "pre_close",
    "change",
    "pct_chg",
    "vol",
    "amount"
])
print(df)

#第二题
import tushare as ts

# 初始化pro接口
pro = ts.pro_api('3171f5df9baa3e897b247de0a2c27026b858e49ba2a53d3280b44010')

# 拉取数据
df = pro.daily(**{
    "ts_code": "",
    "trade_date": "",
    "start_date": 20250301,
    "end_date": 20250331,
    "offset": "",
    "limit": ""
}, fields=[
    "ts_code",
    "trade_date",
    "open",
    "high",
    "low",
    "close",
    "pre_close",
    "change",
    "pct_chg",
    "vol",
    "amount"
])
print(df)
import pandas as pd

# 转换日期格式
df['trade_date'] = pd.to_datetime(df['trade_date'], format='%Y%m%d')

# 按股票代码和时间排序
df = df.sort_values(by=['ts_code', 'trade_date'])

# 填充可能存在的缺失值（示例用收盘价前向填充）
df['close'] = df.groupby('ts_code')['close'].ffill()

# 计算移动平均线（分组处理）
df['ma5'] = df.groupby('ts_code')['close'].transform(
    lambda x: x.rolling(5, min_periods=1).mean()
)
df['ma10'] = df.groupby('ts_code')['close'].transform(
    lambda x: x.rolling(10, min_periods=1).mean()
)
# 计算RSI函数（14日周期）
def calculate_rsi(data, window=14):
    delta = data.diff()
    gain = delta.where(delta > 0, 0)
    loss = -delta.where(delta < 0, 0)

    # 计算平均增益和平均损失
    avg_gain = gain.rolling(window, min_periods=1).mean()
    avg_loss = loss.rolling(window, min_periods=1).mean()

    rs = avg_gain / avg_loss
    rsi = 100 - (100 / (1 + rs))
    return rsi
# 应用RSI计算
df['rsi'] = df.groupby('ts_code')['close'].transform(calculate_rsi)
# 结果展示
print(df[['ts_code', 'trade_date', 'close', 'ma5', 'ma10', 'rsi']].tail(10))

#第三题
import pandas as pd

# 确保数据已按股票代码和日期排序
df = df.sort_values(['ts_code', 'trade_date'])

# 计算前一天的MA5和MA10（用于判断金叉）
df['prev_ma5'] = df.groupby('ts_code')['ma5'].shift(1)
df['prev_ma10'] = df.groupby('ts_code')['ma10'].shift(1)

# 找出5日线上穿10日线的股票（当日ma5>ma10且前日ma5<=ma10）
golden_cross = df[
    (df['ma5'] > df['ma10']) &
    (df['prev_ma5'] <= df['prev_ma10'])
]

# 获取最近交易日（2025年3月31日）出现金叉的股票
latest_date = pd.to_datetime('20250331', format='%Y%m%d')
latest_golden_cross = golden_cross[golden_cross['trade_date'] == latest_date]

# 输出结果
print("5日线上穿10日线的股票列表（2025年3月31日）：")
print(latest_golden_cross[['ts_code', 'trade_date', 'close', 'ma5', 'ma10']])

